package com.dmlll.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmlll.VO.HospitalVO;
import com.dmlll.common.DataGridView;
import com.dmlll.common.ResultObj;
import com.dmlll.domain.Hospital;
import com.dmlll.domain.Purchase;
import com.dmlll.service.HospitalService;
import com.dmlll.service.PurchaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dmLll
 * @since 2021-03-31
 */
@RestController
@RequestMapping("hospital")
public class HospitalController {
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private PurchaseService purchaseService;
    @RequestMapping("/getHospitalById")
    public Hospital getHospitalById(Integer id){
        Hospital hospital = hospitalService.getById(id);
        return hospital;
    }
    @RequestMapping("loadAllHospital")
    public List<Hospital> loadAllHospital(){
        return  hospitalService.list();
    }
    @RequestMapping("loadHospital")
    public DataGridView loadHospital(HospitalVO hospitalVO){
        QueryWrapper<Hospital> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(hospitalVO.getHospitalName()),"hospital_name",hospitalVO.getHospitalName());
        IPage<Hospital> page = hospitalService.page(new Page<>(hospitalVO.getPage(), hospitalVO.getLimit()),queryWrapper);
        return  new DataGridView(page.getTotal(),page.getRecords());
    }
    @RequestMapping("add")
    public ResultObj add(Hospital hospital){
        try {
            hospitalService.save(hospital);
        } catch (Exception e) {
            return ResultObj.ADD_ERROR;
        }
        return ResultObj.ADD_SUCCESS;
    }
    @RequestMapping("update")
    public ResultObj update(Hospital hospital){
        try {
            hospitalService.updateById(hospital);
        } catch (Exception e) {
            return ResultObj.UPDATE_ERROR;
        }
        return ResultObj.UPDATE_SUCCESS;
    }
    @RequestMapping("delete")
    public ResultObj delete(Hospital hospital){
        try {
            List<Purchase> hospitals = purchaseService.list(new QueryWrapper<Purchase>().eq("hospital_id", hospital.getId()));
            if (hospitals.size()>0){
                return ResultObj.DELETE_HAVE_PURCHASE;
            }
            hospitalService.removeById(hospital);
        } catch (Exception e) {
            return ResultObj.DELETE_ERROR;
        }
        return ResultObj.DELETE_SUCCESS;
    }
}

